import api from '../../../fetch/api'

export default {
  data() {
    return {
      isLimitEdit: false,
      editTitle: '',
      manageCostTableData: [], //管理设置table数据
      isShowTable: true,
      isNeedTree: 'show'
    }
  },
  created() {
   
  },
  computed: {
    
  },
  methods: {
    // 重新生成按钮
    reBuild(){
      this.$refs.myReBuildBtn.reBuild()
    },
    getManageCostModalData(){ //获取管理费设置列表数据
      var _this = this;
      api.fetchGet('/monthTicketFinance/list.do',{}).then(res=>{
        if(res.data!=false){ //数组不为空
          let arrList = res.data;
          _this.manageCostTableData = [];
          for(let i = 0; i<arrList.length; i++){
            let obj = {};
            obj.id = arrList[i].id;
            obj.name = arrList[i].name;
            obj.parkUid = arrList[i].parkUid;
            obj.parkName = arrList[i].parkName;
            obj.type = arrList[i].type;
            obj.monthTicketIdList = arrList[i].monthTicketIdList;
            obj.manaCost = arrList[i].manaCost;
            _this.manageCostTableData.push(obj);
          }
        }
      },err=>{});
    },
    getMonthlyTicketList(financeId){ //获取月票列表数据
      var _this = this;
      var params = {};
      if(financeId!=''){
        params.financeId = financeId
      }
      api.fetchGet('/monthTicketFinance/getMonthTicketList.do',params).then(res=>{
        if(res.data!=false){
          _this.monthlyTicketList = [];
          let arrList = res.data;
          for(let i = 0; i<arrList.length; i++){
            let obj = {};
            obj.id = arrList[i].id;
            obj.ticketName = arrList[i].ticketName; 
            _this.monthlyTicketList.push(obj);
          }
        }
      },err=>{});
    },
    ManageCostModal_open(){
      var _this = this;
      this.getManageCostModalData();
      _this.toOpenModal('ManageCostModal', 1);
    },
    EditManageCostModal_save(event, formName){
      var _this = this;
      _this.$refs['editManageCost_form'].validate((valid) => {
        if(valid){
          let params = {};
          params.id = _this.EditManageCostModalData.id;
          params.name = _this.EditManageCostModalData.monthlyTicketType;
          params.parkUid = _this.EditManageCostModalData.parkUid;
          params.parkName = _this.EditManageCostModalData.parkName;
          params.type = _this.EditManageCostModalData.isChoosedMonthlyTicket;
          params.monthTicketIdList = _this.EditManageCostModalData.monthlyTicketList;
          params.manaCost = _this.EditManageCostModalData.manageCost;
          if(_this.EditManageCostModalData.type=='add'){
            var url = '/monthTicketFinance/add.do';
          }else{
            var url = '/monthTicketFinance/update.do';
          }
          api.fetchPost(url,params).then(response=>{
            console.log('EditManageCostModal_save ==== response', response);
            if (response.status == 1) {
              // icon: 0:普通提示 1：正确的提示 2： 错误提示
              // time: 不填默认1000ms
              _this.showToast(response.message, 1, 2000);
              _this.resetForm('editManageCost_form');
              _this.closed('EditManageCostModal');
              _this.getManageCostModalData();
            } else {
              _this.showToast(response.message, 2, 2000)
              return;
            }
          },err => {
            console.log(err);
          })
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /**
     * @param {标识:1新增;2编辑;3查看} mark 
     * @param {记录主键} id 
     */
    EditManageCostModal_open(mark,id){
      var _this = this;
      _this.EditManageCostModalData = {
        type:'add',
        parkList: [], //选择的停车场value
        inputParks: [], //选择的停车场name
        monthlyTicketList: [], //选择的月票value
        inputMonthlyTicket: [], //选择的月票name
        id:'', //主键id
        parkUid: '', //停车场uuid
        parkName:'', //选择停车场的名称
        monthlyTicketType:'', //月票归类名称
        isChoosedMonthlyTicket:0, //是否选择月票
        inputMonthlyTicketstr:'', //选择的月票
        monthlyTicketListStr: "",
        manageCost:0, //归类管理费
      };
      _this.isLimitEdit = false;
      if (id!=undefined) {
        this.getSingleManageCostRecord(id);
        if(mark==3){
          _this.isLimitEdit = true;
          _this.editTitle = '查看';
        }else if(mark==2){
          _this.EditManageCostModalData.type = 'edit';
          _this.editTitle = '修改';
        }
      }else{
        if(mark==1){
          _this.editTitle = '新增';
        }
      }
      _this.toOpenModal('EditManageCostModal', 1);
    },
    getSingleManageCostRecord(id){ //查看or编辑时 获取单条记录
      var _this = this;
      api.fetchGet('/monthTicketFinance/get.do',{id:id}).then(res=>{
        if(res.data){
          var initData = res.data;
          _this.EditManageCostModalData.id = initData.id
          _this.EditManageCostModalData.parkUid = initData.parkUid
          _this.EditManageCostModalData.parkName = initData.parkName
          _this.EditManageCostModalData.monthlyTicketType = initData.name
          _this.EditManageCostModalData.isChoosedMonthlyTicket = initData.type
          _this.EditManageCostModalData.manageCost = initData.manaCost
          if(initData.type==0){ //月票
            _this.EditManageCostModalData.monthlyTicketList = initData.monthTicketIdList //选择的月票id列表
            _this.EditManageCostModalData.inputMonthlyTicketstr = initData.monthTicketNameList.join(','); //选择的月票名称
            _this.EditManageCostModalData.monthlyTicketListStr = initData.monthTicketIdList.join(',')
          }
        }
      })
    },
    openSelectMonthlyTicketModal(){
      var _self = this;
      this.getMonthlyTicketList(_self.EditManageCostModalData.id);
      _self.toOpenModal('selectMonthlyTicketModal',2);
    },
    openSelectParkModal() {
      var _self = this;
      _self.toOpenModal('selectParkModal', 2);
      this.initParkTree("ParkTree");
    },
    initParkTree(treeId) {
      var _self = this;
      api.fetchGet('/parkingBaseData/getParkingBaseDataTree.do', {})
        .then(res => {
          console.log('treetreetreetreetree', res)
          var data = res;
          if (data != null) {
            var nodes = data.data;
            var jsonStr = JSON.stringify(nodes);

            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            nodes = JSON.parse(jsonStr);
            var settings = {
              check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
              },
              view: {
                showIcon: false,
                showLine: false,
              },
              callback: {
                onClick: function (event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                },
              }
            };
            $.fn.zTree.destroy("ParkTree");

            var treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
            treeObj.expandAll(true);

          } else {
            _self.showToast('暂时没有停车场可选', 2, 3000);
          }
        }, err => {})

    },
    selectParkSure() {
      var self = this,
        nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      var parkList = new Array();
      for (var i = 0; i < nodes.length; i++) {
        if (!nodes[i].isArea) {
          parkList.push(nodes[i]);
        }
      }
      if (parkList.length <= 0) {
        // icon: 0:普通提示 1：正确的提示 2： 错误提示
        // time: 不填默认1000ms
        this.showToast('请选择一个停车场', 0, 2000)
        return;
      }
      self.EditManageCostModalData.parkUid = parkList[0].parkId;
      self.EditManageCostModalData.parkName = parkList[0].name;
      self.closed('selectParkModal', 2);
    },
    selectMonthlyTicketSure() {
      var _this = this;
      var arrObj = $('#MonthlyTicketTree > li > input[type=checkbox]:checked');
      _this.EditManageCostModalData.monthlyTicketList = [];
      _this.EditManageCostModalData.inputMonthlyTicket = [];
      if(arrObj.length <= 0){
        this.showToast('请选择一个月票', 0, 2000)
        return;
      }
      arrObj.each(function(){
        _this.EditManageCostModalData.monthlyTicketList.push(this.value);
        _this.EditManageCostModalData.inputMonthlyTicket.push(this.name);
      });
      if (_this.EditManageCostModalData.inputMonthlyTicket.length > 0) {
        _this.EditManageCostModalData.inputMonthlyTicketstr = _this.EditManageCostModalData.inputMonthlyTicket.join(',')
      } 
      _this.closed('selectMonthlyTicketModal', 2);
    },
    getList() {
      if (!this.searchParams.query_chargeDateStart) {
        this.showToast('请选择时间区间');
        return false;
      }
      if(this.otherParams.query_parkId==undefined){
        this.showToast('请选择停车场');
        this.tbodysInfo = [];
        return false;
      }
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.getItemList(params);
    },
    getItemList(aparams) { //查询列表
      let _that = this;
      api.fetchGet('/monthTicketFinance/getStats.do', aparams).then(res => {
          let data = res.data;
          _that.changeTableData(data);
      }, err => {})
    },
    changeTableData(data) { //更改tbodysInfo theadsInfo数据
      let self = this;
      self.tbodysInfo = [];
      self.theadsInfo[3].children = [];
      self.theadsInfo[4].children = [];
      if($.isEmptyObject(data)==false){
        for(let key in data){
          let rows = data[key]
          let firstRow = rows[0]
          //固定表头
          let theadFinanceList = firstRow.financeList
          let theadLen = theadFinanceList.length
          for(let i = 0; i<theadLen; i++){
            let theadIncomeObj = {}
            theadIncomeObj.index = i
            theadIncomeObj.isShow = false
            theadIncomeObj.prop = 'income-'+i
            theadIncomeObj.text = theadFinanceList[i].financeName
            theadIncomeObj.minWidth = 110
            self.theadsInfo[3].children.push(theadIncomeObj)
            let theadPaymentObj = {}
            theadPaymentObj.index = i
            theadPaymentObj.isShow = false
            theadPaymentObj.prop = 'payment-'+i
            theadPaymentObj.text = theadFinanceList[i].financeName
            theadPaymentObj.minWidth = 110
            self.theadsInfo[4].children.push(theadPaymentObj)
          }
          let theadIncomeObj = {}
          theadIncomeObj.index = theadLen
          theadIncomeObj.isShow = false
          theadIncomeObj.prop = 'income'
          theadIncomeObj.text = '收入合计'
          theadIncomeObj.minWidth = 110
          self.theadsInfo[3].children.push(theadIncomeObj)
          let theadPaymentObj = {}
          theadPaymentObj.index = theadLen
          theadPaymentObj.isShow = false
          theadPaymentObj.prop = 'payment'
          theadPaymentObj.text = '支出合计'
          theadPaymentObj.minWidth = 110
          self.theadsInfo[4].children.push(theadPaymentObj)
          //表格数据
          for(let i=0; i<rows.length; i++){
            let rowData = rows[i]
            let rowObj = {}
            rowObj.date = rowData.date
            rowObj.parkName = rowData.parkName
            rowObj.income = rowData.income
            rowObj.payment = rowData.payment
            rowObj.realment = rowData.realment
            let financeList = rowData.financeList
            let len = financeList.length
            for(let j = 0; j<len; j++){
              rowObj['income-'+j] = financeList[j].income
              rowObj['payment-'+j] = financeList[j].payment
            }
            self.tbodysInfo.push(rowObj)
          }
        }      
      }
      self.isShowTable = false;
      this.$nextTick(() => {
        self.isShowTable = true
      });
    },
    filterMultiCheck(selectionArr) { //必须定义获取多列的方法
      let result = [];
      selectionArr.map((item) => {
        result.push(item.id);
      });
      return result;
    },
    handleSearchChange(item) {
      switch (item.name) {
        case 'timeDim':
          this.changeReportDimension(item);
          break;
      }
    },
    getReportDetailPagination(curPage, pageSize) {
      this.tmpdetailModalData.pageNumber = curPage;
      this.tmpdetailModalData.pageSize = pageSize ? pageSize : this.tmpdetailModalData.pageSize;
      this.tmpdetail_list();
      // this.getTraderReportDetailList(this.tmpdetailModalData.searchParams);
    },
    changeReportDimension(item) {
      let value = item.value,
        ThisSearchItem = this.searchList[0];
      // var today = [new Date(moment().format('YYYY-MM-DD 00:00:00')), new Date(moment().add(1, 'days').format('YYYY-MM-DD 00:00:00'))];
      var today = new Date(moment().subtract(1, 'days').format('YYYY-MM-DD 00:00:00'));
      var month = new Date(moment().subtract(1, 'months').format('YYYY-MM-DD 00:00:00'));
      var year = new Date(moment().format('YYYY-MM-DD 00:00:00'));
      switch (value) {
        case 'DATE':
          ThisSearchItem.style = {
            width: '360px'
          };
          ThisSearchItem.pickerType = 'daterange';
          ThisSearchItem.format = 'yyyy-MM-dd';
          ThisSearchItem.value = today;
          break;
        case 'MONTH':
          ThisSearchItem.style = {
            width: '185px'
          };
          ThisSearchItem.pickerType = 'month';
          ThisSearchItem.format = 'yyyy-MM';
          ThisSearchItem.value = month;
          break;
        case 'YEAR':
          ThisSearchItem.style = {
            width: '125px'
          };
          ThisSearchItem.pickerType = 'year';
          ThisSearchItem.format = 'yyyy';
          ThisSearchItem.value = year;
          break;
      }
    },
  }
}
